import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Index from '../components/Index.vue'
import UserManage from'../components/UserManage.vue'
import UserHobby from '../components/UserHobby.vue'
import axios from 'axios'
Vue.use(VueRouter) 

// 定义路由规则
const routes = [
    {
      path: '/',
      redirect:'/login'
    },
    {   
      path: '/login',
      component: Login
    },
    {
      path: '/index',
      component: Index,
      children: [
        {
          path:'usermanage',
          component: UserManage
        },
        {
          path: 'userhobby',
          component: UserHobby
        }
      ]
    }
]

// 创建路由实例
const router = new VueRouter({
  routes // 传入路由规则
})

// router.beforeEach((to,from,next)=>{
//   //如果是登录界面,就移除localstore中的user,否则都要读取前端保存的token到后端进行检验
//   if(to.path.startsWith("/login")){
//     window.localStorage.removeItem("user")
//     next()
//   }else{//否则读取localstore中的user字符串,将其转换为user对象
//     let userstring = localStorage.getItem("user");
//     const user = JSON.parse(userstring)
//     console.log("-------------------",user)
//     if(user==null){
//       next({path:"/login"})
//     }else{//如果user对象非空,则像后端发起检验请求
//       console.log("-------------------",user.token)
//       axios({
//         url:'http://localhost:9090/user/checkToken',
//         method: "get",
//         headers: {
//           token:user.token
//         }
//       }).then(Response=>{
//         if(Response.data=="fail"){
//           console.log("校验失败")
//           next({path:"/user/login"})
//           }else
//             next()
//       })  
//     }
//   }
// })

export default router 